package co.angluzha.commons.redis.utils;

import co.angluzha.commons.core.utils.ApplicationUtils;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

/**
 * co.angluzha.commons.redis.uilts文档说明
 *
 * @author Angluzha
 * @version 2022/11/23
 */
@Slf4j
public class RedisLock {
    private static RedissonClient redissonClient;
    private static ThreadLocal<RLock> threadLock = new ThreadLocal<>();

    static{
        redissonClient = ApplicationUtils.getBean(RedissonClient.class);
    }

    public static void lock(String name){
        RLock lock = redissonClient.getLock(name);
        log.info("[lock] Redis{}锁尝试获取",name);
        lock.lock();
        log.info("[lock] Redis{}锁已获取",name);
        threadLock.set(lock);
    }

    public static void unlock(){
        RLock lock = threadLock.get();
        if (lock!=null&&lock.isLocked()){
            lock.unlock();
            threadLock.remove();
            log.info("[lock] Redis{}锁已释放",lock.getName());
        }
    }
}
